package com.gan.simple_init.common.filter;


import com.gan.simple_init.model.user.entity.LoginUser;
import com.gan.simple_init.service.impl.UserDetailsServiceImpl;
import com.gan.simple_init.util.JwtTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 自定义security Jwt拦截器，如果有 token 则将其中的信息&权限存到 SecurityContextHolder 上
 *
 * @author gbw
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Resource
    private UserDetailsServiceImpl userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        // 获取真正token
        String token = httpServletRequest.getHeader("token");
        // 判断token是否合法
        if (StringUtils.isNotEmpty(token) && StringUtils.isNotEmpty(jwtTokenUtil.getUserNameFromToken(token)) && Objects.isNull(SecurityContextHolder.getContext().getAuthentication())) {
            LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(jwtTokenUtil.getUserNameFromToken(token));
            boolean tokenFlag = jwtTokenUtil.getTokenFlag(token);
            // 验证token是否有效,如果redis中存在token则需要对redis中的token相对应
            if (jwtTokenUtil.validateToken(token, loginUser) && tokenFlag) {
                UsernamePasswordAuthenticationToken AuthenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                // 重新设置用户权限
                AuthenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
                SecurityContextHolder.getContext().setAuthentication(AuthenticationToken);
            }
        }
        // 将请求放行给下一个拦截器
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
